package com.gz.rocketmq.order;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * 顺序消费生产者
 */
public class OrderProducer {

    public static void main(String[] args) throws Exception {
        List<OrderInfo> orderInfos = OrderInfo.initOrder();
        DefaultMQProducer producer = new DefaultMQProducer("rocketmq_order_group");
        producer.setNamesrvAddr("192.168.36.128:9876");
        producer.start();

        orderInfos.forEach(e->{
            Message message = new Message("order_topic","orderTag",String.valueOf(e).getBytes(StandardCharsets.UTF_8));
            try {
                SendResult send = producer.send(message, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                        int orderId = (int) o;
                        int idx = orderId % list.size();
                        return list.get(idx);
                    }
                }, e.getOrderId());
                System.out.println(send);
            } catch (Exception mqClientException) {
                mqClientException.printStackTrace();
            }
        });

        producer.shutdown();
    }

}
